package com.example.common.aspect;


import com.example.common.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;


@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Autowired
    private HttpServletRequest Request;
    @Pointcut("execution(* *..mapper..*(..)) && @annotation(com.example.common.annotation.AutoFill)")
    public void autoFillPointCut(){
    }

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){

        //获取实体
        Object[] args = joinPoint.getArgs();
        Object entity = args[0];
        //准备数据
        LocalDateTime now = LocalDateTime.now();
        String admin = UserContext.getUser();
        try {
            Method setLastOperationTime = entity.getClass().getDeclaredMethod("setLastOperationTime", LocalDateTime.class);
            Method setLastOperator = entity.getClass().getDeclaredMethod("setLastOperator", String.class);
            setLastOperator.invoke(entity,(String)admin);
            setLastOperationTime.invoke(entity,now);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

    }

}
